# -*- coding: utf-8 -*-

"""
PyoCDVD (http://code.google.com/p/pyocdvd/)
Media Organizer (CD, DVD, etc)

Developers:
    Bruno Pitteli Gonçalves <scorninpc(*)gmail(*)com>
    Paul Eipper <lkraider(*)gmail(*)com>

Licence: GNU GENERAL PUBLIC LICENSE v3

"""

import os
import cdrom
import database.database_api
import interface.glade_gui
import datetime
from plugins import *

NT = (os.name == 'nt')
POSIX = (os.name == 'posix')

class PyoCDVD:

    def __init__(self):
        if NT or POSIX:
            self.cdrom = cdrom.PyoCDVD_Cdrom()
            self.db = database.database_api.PyoCDVD_Database()
            self.gui = interface.glade_gui.PyoCDVD_Interface(self)
            self.plugin_list = plugin.PyoCDVD_Plugin.__subclasses__()
            self.gui.display()

    def search_files(self, query):
        data = self.db.select_discs_with_file(query)
        return data.keys()

    def list_all_discs(self):
        return self.db.select_all_discs()

    def scan_devices(self):
        '''Scan the devices and list its files.
        Return an error (if any) and a list of files from the device.'''
        devices = self.cdrom.list_devices()
        if len(devices) <= 0:
            no_device_found = 'Não foi possivel encontrar um dispositivo.'
            if POSIX:
                no_device_found += ' Certifique que o cdrom esteja montado.'
            return no_device_found, None
        elif len(devices) == 1:
            device = devices[0]
        elif len(devices) > 1:
            response, device = self.gui.dialogs.device_selection(devices)
            if not response:
                return None, []
        if POSIX:
            device = self.cdrom.mount_point(device)
        file_list = self.cdrom.list_files(device)
        if not file_list:
            return 'Certifique que o cdrom esteja pronto.', None
        return None, file_list

    def save_disc(self, disc_name, comments, file_list):
        '''Save the file and disc data on the database.
        Return an error (if any) and a status message.'''
        # Verify data
        if not disc_name:
            return 'O campo "Nome do disco" é obrigatório.', None
        if not file_list:
            return 'É necessário ao menos um arquivo.', None
        for line in file_list:
            selection = line[0]
            if selection:
                break
        if not selection:
            return 'É necessário ao menos um arquivo.', None
        # Save data
        disc_data = {'nome': disc_name,
                     'data_cadastro': datetime.datetime.now().isoformat(),
                     'comentario': comments}
        disc_id = self.db.insert_disc(disc_data)
        total = 0
        metadata = {}
        for line in file_list:
            if line[0]:
                filepath = line[1]
                # Apply plugins
                for plugin in self.plugin_list:
                    plugin_meta = plugin().run(filepath)
                    metadata.update(plugin_meta)
                # Dump the drive letter before saving
                # TODO: POSIX should only save relative path aswell
                if NT:
                    filepath = os.path.splitdrive(filepath)[1]
                self.db.insert_file(disc_id, filepath, metadata)
                total += 1
        self.db.commit()
        return None, 'Disco %s gravado com %s arquivos' % (disc_name, total)


if __name__ == "__main__":
    PyoCDVD = PyoCDVD()